var tips = {
    //通用对话框
    alert: function(msg, act) {
        if (frameElement == null || frameElement.api == undefined) {
            this.alert1(msg, act);
        } else {
            var api = frameElement.api,
                W = api.opener;
            W.$.dialog.alert(msg, function() {
                setTimeout(function() {
                    if (typeof act == 'function') {
                        act();
                    } else {
                        eval(act);
                    }
                }, 1);
            });
        }
    },
    alert1: function(msg, act) {
        $.dialog.alert(msg, function() {
            if (typeof act == 'function') {
                act();
            } else {
                eval(act);
            }
        });
    },
    alertByTime: function(src, msg, t) {
        if (src == 1) {
            src = "success.gif";
        } else {
            src = "error.gif";
        }
        if (t == ''){ t = 2; }
        $.dialog.tips(msg, t, src, function() {});

    },
    confirm: function(msg, fun1, fun2) {
        if (frameElement == null || frameElement.api == undefined) {
            this.confirm1(msg, fun1, fun2);
        } else {
            var api = frameElement.api,
                W = api.opener;
            W.$.dialog.confirm(msg, function() {
                setTimeout(function() {
                    eval(fun1);
                }, 1);
            }, function() {
                setTimeout(function() {
                    eval(fun2);
                }, 1);
            });
        }
    },
    confirm1: function(msg, fun1, fun2) {
        $.dialog.confirm(msg, function() {
            if (typeof fun1 == 'function') {
                fun1();
            } else {
                eval(fun1);
            }
        }, function() {
            if (typeof fun2 == 'function') {
                fun2();
            } else {
                eval(fun2);
            }
        });
    },
    message: function(ico, msg, fun) {
        if (frameElement == null || frameElement.api == undefined) {
            this.message1(ico, msg, fun);
        } else {
            var api = frameElement.api,
                W = api.opener;
            W.$.dialog.tips(msg, 2, ico, function() {
                setTimeout(function() {
                    eval(fun);
                }, 1);
            });

        }
    },
    message1: function(ico, msg, fun) {
        $.dialog.tips(msg, 2);
        setTimeout(function() {
            eval(fun);
        }, 2000);
    },
    tips: function(title, msg, w, h) {
        $.dialog({
            title: title,
            content: msg,
            width: w,
            height: h,
            max: false,
            min: false
        });
    },
    /**
     * 侧边提示框（不可跳转）
     * @param msg
     * @param title
     */
    msg: function (msg , title){
        if(!title){
            title = '提示信息'
        };
        $.gritter.add({
            title:title,
            text:msg,
            time:1500,
            speed:1000,
            sticky: false,
        });
    },
    //'error','info','success','warning'
    toastrBottomRight:function (type , msg , time) {
        if (time === undefined) {
            time = 2000;
        }
        toastr.options.timeOut = time;
        toastr.options.extendedTimeOut = 500;
        toastr.options.positionClass = "toast-bottom-right";
        toastr[type](msg);
    },
    toastrTopRight:function (type , msg , time) {
        if (time === undefined) {
            time = 2000;
        }
        toastr.options.timeOut = time;
        toastr.options.extendedTimeOut = 500;
        toastr.options.positionClass = "toast-top-right";
        toastr[type](msg);
    }
};


// 常用工具方法
var tools = {
    setData: function (key , value) {
        if (typeof value == 'object') {
            value = JSON.stringify( value );
        }
        return localStorage.setItem(key,value);
    },
    getData: function (key) {
        var value  =  localStorage.getItem(key);
        if (tools.isJson(value)) {
            value = JSON.parse(value);
        }
        return value;
    },
    clearAllsData: function () {
        localStorage.clear();
    },
    clearField: function (key) {
        localStorage.removeItem(key);
    },
    isJson: function (str) {
        if (typeof str == 'string') {
            try {
                var obj=JSON.parse(str);
                if(str.indexOf('{')>-1){
                    return true;
                }else{
                    return false;
                }

            } catch(e) {
                // console.log(e);
                return false;
            }
        }
        return false;
    },
    /**
     * 实例表单验证插件
     * @param options
     * @param messagetype
     * @returns {*}
     */
    databind: function (options) {
        if (!options) options = {};
        var def = {
            errorHandle:function (message , thisEle , tipsEle) {
                tips.alert(message);
            }
        };
        options = $.extend(def , options);
        return $.databind(options);
    },
    ajaxRequest: function (defaults) {
        var options = new Object();

        options.type  = defaults.type;
        options.url   = defaults.url;
        options.async = defaults.async;
        options.data =  $.extend({} , defaults.data);
        if (!defaults.error) {
            defaults.error = function (result) {
                if (result) {
                    tips.alert1(result.msg);
                } else {
                    tips.alert1("网络错误，请刷新页面重试!");
                }
            }
        }
        options.error = defaults.error;
        options.success = function (result) {
            if (result.status != 0) {
                defaults.error && defaults.error(result);
                return;
            }
            defaults.success && defaults.success(result);
        };
        $.ajax(options);
    },
    /**
     * 上传文件请求
     * @param {Object} options  参数对象
     * options.files 	  上传文件框元素
     * options.filesdata  上传文件数据
     * options.ufield     上传字段名称
     * options.url		  提交网址
     * options.success    成功回调
     * options.error 	  失败回调
     */
    ajaxUploadFile: function (options) {
        var thisData = new FormData();
        var ufield   = options.hasOwnProperty('ufield') ? options.ufield : 'image';
        //携带数据
        if (options.hasOwnProperty('data') && (options.data).constructor == Object) {
            for (e in options.data){
                thisData.append(e , options.data[e]);
            }
        }
        if(options.files) {
            var files = $(options.files).prop('files');
            thisData.append(ufield, files[0]);
        }
        if(options.filesdata) {
            if (options.filesdata.constructor == FileList) {
               for (let i=0;i<options.filesdata.length;i++) {
                   thisData.append(`${ufield}[]`, options.filesdata[i]);
               }
            } else {
                thisData.append(ufield, options.filesdata);
            }
        }
        //异步
        var async = options.hasOwnProperty('async') ? options.async : true;
        var defoptions = {
            url:options.url,
            type:'POST',
            data:thisData,
            processData:false,
            contentType:false,
            async:async
        };
        if (options.hasOwnProperty('success')) {
            defoptions.success = options.success;
        }
        if (options.hasOwnProperty('error')) {
            defoptions.error = options.error;
        }
        if (options.hasOwnProperty('xhr')) {
            defoptions.xhr = options.xhr;
        }
        //run
        $.ajax(defoptions);
    },
    /**
     * 搜索某个值是否存在数组之内
     * @param needle 搜索的值
     * @param haystack 被搜索的数组
     * */
    in_array: function (needle, haystack) {
        var length = haystack.length;
        for(var i = 0; i < length; i++) {
            if(haystack[i] == needle) return true;
        }
        return false;
    },
    /**
     * 获取地址栏参数
     * @param par   地址栏参数标识
     * @returns {*}
     */
    getPar: function(par){
        //获取当前URL
        var local_url = document.location.href;
        //获取要取得的get参数位置
        var get = local_url.indexOf(par +"=");

        if(get == -1){
            return false;
        }
        var flag =local_url.slice(par.length + get - 1);
        var flag_sure = local_url.slice(get-1 , get);
        if(flag_sure !=="?" && flag_sure !=="&"){
            return false;   //去除相似的
        }
        //截取字符串
        var get_par = local_url.slice(par.length + get + 1);
        //判断截取后的字符串是否还有其他get参数
        var nextPar = get_par.indexOf("&");
        if(nextPar != -1){
            get_par = get_par.slice(0, nextPar);
        }
        return get_par;
    },
    /**
     * @param ele
     * @param state
     * @returns {jQuery|HTMLElement}
     */
    disabled:function (ele , state) {
        $(ele).prop('disabled' , state);
        return $(ele);
    }
};


/**
 * @type {{encode: base64.encode, decode: base64.decode}}
 */
var base64 = {
    encode:function (str) {
        try {
            return str ? window.btoa(window.encodeURIComponent(str)) : null;
        } catch (e) {
            return null;
        }
    },
    decode:function (str) {
        try {
            return str ? window.decodeURIComponent(window.atob(str)) : null;
        } catch (e) {
            return null;
        }
    }
}

var json = {
    filter:function (json) {
        return json ? json.replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g , "\\t") : '';
    }
};


/**
 * @param format
 * @returns {string}
 */
function date (format) {
    if (!format) format = 'Y-m-d H:i:s';
    let date = new Date();
    //年
    let year = date.getFullYear();
    //月
    let month=date.getMonth()+1;
    //日
    let day=date.getDate();
    //时
    let hh = date.getHours();
    //分
    let mm = date.getMinutes();
    //秒
    let ss = date.getSeconds();
    return format.replace(/Y/g , year).replace(/m/g , month).replace(/d/g , day).replace(/H/g , hh).replace(/i/g , mm).replace(/s/g , ss);
}



function LayerIFrameBox(options){
    var defaults = {
        type: 2,
        title: '',
        shadeClose: true,
        shade: 0.8,
        area: ['380px', '90%'],
        maxmin:true
    };
    var splis = $.extend(defaults , options);
    layer.open(splis);
}

/**
 * 删除数组中指定的值
 * @param arr
 * @param val
 */
function removeArrayValue(arr, val) {
    for(var i=0; i<arr.length; i++) {
        if(arr[i] == val) {
            arr.splice(i, 1);
            break;
        }
    }
    return arr;
}


function allstrlen(str) {
    let cnt = 0;
    for(i=0; i<str.length; i++) {
        let value = str.charCodeAt(i);
        if(value < 0x080) {
            cnt += 1;
        } else if( value < 0x0800) {
            cnt += 1;
        } else {
            cnt += 1;
        }
    }
    return cnt;
}


/**
 * 设置Cookie
 * @param key
 * @param value
 * @param t seconds
 */
function setCookie(key , value , t){
    let oDate = new Date();
    oDate.setDate(oDate.getDate() + t);
    document.cookie = key+"="+value+"; expires="+oDate.toDateString();
}

/**
 * 获取Cookie
 * @param key
 * @returns {string}
 */
function getCookie(key){
    var arr1=document.cookie.split("; ");
    for(var i=0;i<arr1.length;i++){
        var arr2=arr1[i].split("=");
        if(arr2[0]==key){
            return decodeURI(arr2[1]);
        }
    }
}

/**
 * 移除Cookie
 * @param key
 */
function removeCookie(key){
    setCookie(key , "" , -1); //把cookie设置为过期
}


/**
 * @param target
 * @returns {string}
 */
function checkType(target) {
    return Object.prototype.toString.call(target).slice(8, -1);
}

/**
 * 深度克隆
 * @param target
 * @returns {*}
 */
function copyObject(target) {
    let result;
    let targetType = checkType(target);
    if (targetType === 'Object') {
        result = {};
    } else if (targetType === 'Array') {
        result = [];
    }else {
        return target;
    }
    //遍历目标数据
    for (let i in target) {
        let value = target[i];
        //判断目标结构里的每一值是否存在对象/数组
        if(checkType(value) === 'Object'||checkType(value) === 'Array'){
            //对象或者数组里嵌套了对象或者数组
            //继续遍历获取到的value值
            result[i] = copyObject(value);
        }else {
            result[i] = value;
        }
    }
    return result;
}

/**
 * @param after
 * @returns {*}
 */
function getFullDateText (after) {
    if (after === undefined) after = false;

    let today = new Date();
    let month = today.getMonth() + 1;
    month = month < 10 ? '0'+month : month;
    let day = today.getDate() < 10 ? '0' + today.getDate() : today.getDate();
    let hours = today.getHours() < 10 ? '0' + today.getHours() : today.getHours();
    let mins = today.getMinutes() < 10 ? '0' + today.getMinutes() : today.getMinutes();
    let secs = today.getSeconds() < 10 ? '0' + today.getSeconds() : today.getSeconds();

    if (after) {
        return today.getFullYear()+String(month)+String(day)+"_"+String(hours)+String(mins)+String(secs);
    } else {
        return today.getFullYear()+String(month)+String(day);
    }
}


/**
 * @returns {number}
 */
function getNowTimestamp() {
    return (new Date()).valueOf();
}


/**
 * 获取当前滚动条位置
 * @returns {{top: *, left: *, width: *, height: *}}
 */
function  scrollPostion() {
    var t, l, w, h;
    if (document.documentElement && document.documentElement.scrollTop) {
        t = document.documentElement.scrollTop;
        l = document.documentElement.scrollLeft;
        w = document.documentElement.scrollWidth;
        h = document.documentElement.scrollHeight;
    } else if (document.body) {
        t = document.body.scrollTop;
        l = document.body.scrollLeft;
        w = document.body.scrollWidth;
        h = document.body.scrollHeight;
    }
    return { top: t, left: l, width: w, height: h };
}

/**
 * @param filename
 * @returns {string}
 */
function getFileSuffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

function changeState(el) {
    if (el.readOnly) el.checked=el.readOnly=false;
    else if (!el.checked) el.readOnly=el.indeterminate=true;
}

//获取textarea中选中的内容
function getSelectText(id) {
    var t = document.getElementById(id);
    if (window.getSelection) {
        if (t.selectionStart != undefined && t.selectionEnd != undefined) {
            return t.value.substring(t.selectionStart, t.selectionEnd);
        } else {
            return "";
        }
    } else {
        return document.selection.createRange().text;
    }
}

/**
 * 防抖动
 * @param func
 * @param wait
 * @returns {Function}
 */
function debounce(func, wait) {
    let lastTime = null;
    let timeout;
    return function() {
        let context = this;
        let now = new Date();
        // 判定不是一次抖动
        if (now - lastTime - wait > 0) {
            setTimeout(() => {
                func.apply(context, arguments);
            }, wait);
        } else {
            if (timeout) {
                clearTimeout(timeout);
                timeout = null;
            }
            timeout = setTimeout(() => {
                func.apply(context, arguments);
            }, wait);
        }
        // 注意这里lastTime是上次的触发时间
        lastTime = now;
    }
}


/**
 * @param $
 * 自定义jQuery扩展方法, 在光标处插入内容
 */
(function ($) {
    "use strict";
    $.fn.extend({
        insertAtCaret : function (myValue) {
            var $t = $(this)[0];
            if (document.selection) {
                this.focus();
                var sel = document.selection.createRange();
                sel.text = myValue;
                this.focus();
            } else
            if ($t.selectionStart || $t.selectionStart == '0') {
                var startPos = $t.selectionStart;
                var endPos = $t.selectionEnd;
                var scrollTop = $t.scrollTop;
                $t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
                this.focus();
                $t.selectionStart = startPos + myValue.length;
                $t.selectionEnd = startPos + myValue.length;
                $t.scrollTop = scrollTop;
            } else {
                this.value += myValue;
                this.focus();
            }
        }
    });
})(jQuery);


/**
 * 显示分页
 * @param {Object} pageArray  分页数据
 * @param {string} Obj 显示的对象
 */
function showpage(pageArray,Obj){
    $(Obj).html("");
    pageArray.nowPage = parseInt(pageArray.nowPage);

    var head,nowTpl,Tpl,lastpage,nextpage,endpage,startPage,endPage;
    var limit = 10; //显示的页码的数量

    head = "<li><span> {totalRows} 条记录 {nowPage}/{totalPage} 页</span></li>";
    nowTpl = "<li><span class='current'>{num}</span></li>";
    Tpl = "<li><a href='javascript:;' p='{num}'>{num}</a></li>";
    lastpage = "<li><a href='javascript:;' p='{num}'>上一页</a></li>";
    nextpage = "<li><a href='javascript:;' p='{num}'>下一页</a></li>";
    startpageTpl = "<li><a href='javascript:;' p='{num}'>首页</a></li>";
    endpageTpl = "<li><a href='javascript:;' p='{num}'>最后一页</a></li>";

    $("#num").text(pageArray.totalRows);

    html = "<ul>";

    head = head.replace(/{totalRows}/,pageArray.totalRows);
    head = head.replace(/{nowPage}/,pageArray.nowPage);
    head = head.replace(/{totalPage}/,pageArray.totalPages);

    html += head;

    if(pageArray.totalPages > 1){
        if(pageArray.nowPage > 1){
            html += startpageTpl.replace(/{num}/g, 1 );
            html += lastpage.replace(/{num}/g, (pageArray.nowPage-1) );
        }

        if(pageArray.totalPages > limit){
            if((pageArray.nowPage + parseInt(limit / 2) ) > pageArray.totalPages){
                startPage = pageArray.totalPages - (limit-1);
                endPage = pageArray.totalPages;
            }else if( (pageArray.nowPage - parseInt(limit / 2) ) <= 1 ){
                startPage = 1;
                endPage = limit;
            }else{
                startPage = pageArray.nowPage - parseInt(limit / 2);
                endPage = pageArray.nowPage + parseInt(limit / 2);
            }
        }else{
            startPage = 1;
            endPage = pageArray.totalPages;
        }

        for(var i=startPage;i<=endPage;i++){
            if(pageArray.nowPage == i){
                html += nowTpl.replace(/{num}/g,i);
            }else{
                html += Tpl.replace(/{num}/g,i);
            }
        }

        if(pageArray.nowPage < pageArray.totalPages){
            html += nextpage.replace(/{num}/g, (pageArray.nowPage+1) );
            html += endpageTpl.replace(/{num}/g, pageArray.totalPages );
        }

    }

    html += "</ul>";
    $(Obj).append(html);
}


/**
 * @param container
 */
function makeExpandingArea(container) {
    var area = container.getElementsByTagName('textarea')[0] ;
    var span = container.getElementsByTagName('span')[0] ;
    if (area.addEventListener) {
        area.addEventListener('input', function() {
            span.textContent = area.value;
        }, false);
        span.textContent = area.value;
    } else if (area.attachEvent) {
        area.attachEvent('onpropertychange', function() {
            var html = area.value.replace(/\n/g,'<br/>');
            span.innerText = html;
        });
        var html = area.value.replace(/\n/g,'<br/>');
        span.innerText = html;
    }
    if(window.VBArray && window.addEventListener) { //IE9
        area.attachEvent("onkeydown", function() {
            var key = window.event.keyCode;
            if(key == 8 || key == 46) span.textContent = area.value;
        });
        area.attachEvent("oncut", function(){
            span.textContent = area.value;
        });//处理粘贴
    }
    container.className += " active";
}


/**
 * @param url
 */
function openNewWindow(url){
    var a = document.createElement('a');
    a.setAttribute('href', url);
    a.setAttribute('style', 'display:none');
    a.setAttribute('target', '_blank');
    document.body.appendChild(a);
    a.click();
    a.parentNode.removeChild(a);
};

/**
 * 下载
 * @param  {String} url 目标文件地址
 * @param  {String} filename 想要保存的文件名称
 */
function download(url, filename) {
    getBlob(url, function (blob) {
        saveAs(blob, filename);
    });
};

/**
 * 获取 blob
 * @param  {String} url 目标文件地址
 * @return {cb}
 */
function getBlob(url, cb) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = function () {
        if (xhr.status === 200) {
            cb(xhr.response);
        }
    };
    xhr.send();
}

/**
 * 保存
 * @param  {Blob} blob
 * @param  {String} filename 想要保存的文件名称
 */
function saveAs(blob, filename) {
    if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
    } else {
        var a = document.createElement('a');
        var body = document.querySelector('body');
        a.href = window.URL.createObjectURL(blob);
        a.download = filename;
        a.style.display = 'none';
        body.appendChild(a);
        a.click();
        body.removeChild(a);
        window.URL.revokeObjectURL(a.href);
    };

}